import tkinter as tk
from tkinter import ttk, messagebox
import random
from PIL import Image, ImageTk, ImageDraw


class ColorBlockApp:
    def __init__(self, root):
        self.root = root
        self.root.title("色块显示程序")
        self.root.geometry("500x400")
        self.root.resizable(False, False)

        # 设置中文字体
        self.setup_fonts()

        # 透明度变量
        self.alpha_value = tk.StringVar(value="1.0")

        # 当前颜色
        self.current_color = None

        # 创建界面组件
        self.create_control_panel()
        self.create_display_area()

    def setup_fonts(self):
        """设置支持中文的字体"""
        default_font = ('SimHei', 10)
        self.root.option_add("*Font", default_font)

    def create_control_panel(self):
        """创建控制面板（文本框和按钮）"""
        control_frame = ttk.Frame(self.root, padding="20")
        control_frame.pack(fill=tk.X)

        # 透明度标签
        ttk.Label(control_frame, text="透明度 (0.0-1.0):").grid(
            row=0, column=0, padx=5, pady=10, sticky=tk.W
        )

        # 透明度输入框
        self.alpha_entry = ttk.Entry(
            control_frame,
            textvariable=self.alpha_value,
            width=10
        )
        self.alpha_entry.grid(row=0, column=1, padx=5, pady=10)

        # 生成按钮
        generate_btn = ttk.Button(
            control_frame,
            text="生成色块",
            command=self.generate_color_block
        )
        generate_btn.grid(row=0, column=2, padx=10, pady=10)

        # 更新透明度按钮
        update_alpha_btn = ttk.Button(
            control_frame,
            text="更新透明度",
            command=self.update_transparency
        )
        update_alpha_btn.grid(row=0, column=3, padx=10, pady=10)

    def create_display_area(self):
        """创建色块显示区域"""
        self.display_frame = ttk.Frame(self.root, padding=20)
        self.display_frame.pack(fill=tk.BOTH, expand=True)

        self.canvas = tk.Canvas(
            self.display_frame,
            width=200,
            height=200,
            bg="#f0f0f0",
            highlightthickness=1,
            highlightbackground="#cccccc"
        )
        self.canvas.pack()

        # 存储图像对象的引用，防止被垃圾回收
        self.image_ref = None

    def validate_alpha(self):
        """验证透明度输入是否有效"""
        try:
            alpha = float(self.alpha_value.get())
            if 0.0 <= alpha <= 1.0:
                return alpha
            else:
                messagebox.showerror("输入错误", "透明度必须在0.0到1.0之间")
                return None
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字")
            return None

    def generate_random_color(self):
        """生成随机RGB颜色"""
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        return (r, g, b)

    def create_transparent_block(self, color, alpha):
        """创建带透明度的色块图像"""
        # 创建100x100的图像，带Alpha通道
        img = Image.new("RGBA", (100, 100), (255, 255, 255, 0))  # 透明背景
        draw = ImageDraw.Draw(img)

        # 将alpha从0-1转换为0-255
        alpha_value = int(alpha * 255)

        # 绘制带透明度的色块
        draw.rectangle(
            [(0, 0), (100, 100)],
            fill=(color[0], color[1], color[2], alpha_value)
        )

        return img

    def generate_color_block(self):
        """生成并显示带透明度的色块"""
        alpha = self.validate_alpha()
        if alpha is None:
            return

        # 生成随机颜色
        self.current_color = self.generate_random_color()

        # 创建带透明度的图像
        img = self.create_transparent_block(self.current_color, alpha)

        # 转换为Tkinter可用的图像
        self.image_ref = ImageTk.PhotoImage(img)

        # 清除已有内容并显示新色块（保持在画布中央）
        self.canvas.delete("all")
        self.canvas.create_image(100, 100, image=self.image_ref)  # 200x200画布的中心

    def update_transparency(self):
        """更新现有色块的透明度，保持位置和颜色不变"""
        if self.current_color is None:
            messagebox.showinfo("提示", "请先生成一个色块")
            return

        alpha = self.validate_alpha()
        if alpha is None:
            return

        # 使用当前颜色创建新的透明度图像
        img = self.create_transparent_block(self.current_color, alpha)
        self.image_ref = ImageTk.PhotoImage(img)

        # 更新显示，保持位置不变
        self.canvas.delete("all")
        self.canvas.create_image(100, 100, image=self.image_ref)


def main():
    root = tk.Tk()
    app = ColorBlockApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()
